# encoding: utf-8
import traceback

import pymysql.cursors


class UcloudDB(object):
    def __init__(self,
                 ip,
                 port=3306,
                 username='root',
                 password='winit2015',
                 db='ucloud_agent'):

        self.config = {
            'host': ip,
            'port': port,
            'user': username,
            'password': password,
            'db': db,
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor,
            'connect_timeout': 10
        }

        self.connection = pymysql.connect(**self.config)

    def commit(self):
        if self.connection is not None:
            self.connection.commit()

    def close(self):

        if self.connection is not None:
            self.connection.close()

    def search_one(self, sql):
        try:

            with self.connection.cursor() as cursor:
                # 执行sql语句，插入记录

                cursor.execute(sql)

                return cursor.fetchone()

        except BaseException, ex:
            print traceback.format_exc()
            print "执行失败了"' 原因:' + ex.message
            return None
        finally:
            self.connection.commit()

    def do_sql(self, sql, param):
        try:

            with self.connection.cursor() as cursor:
                # 执行sql语句，插入记录

                cursor.execute(sql, param)

        except BaseException, ex:
            print traceback.format_exc()
            print "执行失败原因:" + ex.message
        finally:
            self.connection.commit()


class UcloudApp(UcloudDB):
    def do_remove(self, app_name, zone_alias):

        _app_id = zone_alias + ":" + app_name

        if self._allready_inserted(app_id=_app_id):
            print '%s已经存在, 删除之' % _app_id
            self._remove_app(app_id=_app_id)

    def do_insert(self, app_name, zone, zone_alias, port, app_type, db_name,
                  mem_level, db_type=None, on_beetle='true'):

        _app_id = zone_alias + ":" + app_name

        if self._allready_inserted(app_id=_app_id):
            print '%s已经存在, 删除之' % _app_id
            self._remove_app(app_id=_app_id)

        print "开搞"
        self._insert_zone_app(app_name=app_name,
                              zone=zone,
                              zone_alias=zone_alias,
                              port=port,
                              db_name=db_name,
                              app_type=app_type,
                              mem_level=mem_level,
                              db_type=db_type,
                              on_beetle=on_beetle)

    def _allready_inserted(self, app_id):
        sql = "SELECT 1 FROM ucloud_agent.app app where app_id = '%s'" % app_id

        result = self.search_one(sql)

        if result is not None:
            return True
        else:
            return False

    def _remove_app(self, app_id):
        sql = "DELETE FROM ucloud_agent.app WHERE app_id = %s"
        self.do_sql(sql=sql, param=app_id)

    def _insert_zone_app(self, app_name, zone, zone_alias, port,
                         mem_level='2',
                         db_name="null",
                         app_type='tomcat',
                         db_type=None,
                         on_beetle='true'):
        sql = "INSERT INTO ucloud_agent.app (app_id, zone_code, app_name, " \
              "db_name, port, app_install_date, version, " \
              "mem_level, app_type, db_type, " \
              "on_beetle, status, created, updated, db_status, " \
              "app_package_create_date, " \
              "db_dump_create_date, db_import_date, " \
              "last_msg, disabled, starting_order) VALUES " \
              "(%s, " \
              "%s, " \
              "%s, " \
              "%s, " \
              "%s, " \
              "null, " \
              "'-1', " \
              "%s, " \
              "%s, " \
              "%s, " \
              "%s, " \
              "null, " \
              "null, " \
              "'2017-03-28 17:04:05', " \
              "'ready', " \
              "null, " \
              "null, " \
              "'2017-03-25 22:04:04', " \
              "null, " \
              "0, " \
              "999999);"

        _app_id = zone_alias + ":" + app_name

        self.do_sql(sql=sql, param=(
            _app_id, zone, app_name, db_name, port, mem_level, app_type,
            db_type, on_beetle))


class UcloudZone(UcloudDB):
    def do_insert(self, zone_code, zone_alias, parent_code, title,
                  order):

        if self._allready_inserted(zone_code=zone_code):
            self._remove_zone(zone_code=zone_code)

        print "开搞zone"
        self.insert_zone(zone_code=zone_code,
                         zone_alias=zone_alias,
                         parent_code=parent_code,
                         title=title,
                         order=order)

    def _allready_inserted(self, zone_code):
        sql = "SELECT 1 FROM ucloud_agent.zone zone where zone_code = '%s'" % zone_code

        result = self.search_one(sql)

        if result is not None:
            return True
        else:
            return False

    def insert_zone(self, zone_code, zone_alias, parent_code, title,
                    order):
        sql = "INSERT INTO ucloud_agent.zone (zone_code, zone_alias, parent_code, zone_title, zone_desc, available, home_path, build_in, created, updated, timezone, zone_alise, order_no) VALUES (" \
              "%s, " \
              "%s, " \
              "%s, " \
              "%s, " \
              "null, " \
              "1, " \
              "null, " \
              "0, " \
              "null, " \
              "null, " \
              "'', " \
              "null, " \
              "%s);"
        self.do_sql(sql=sql,
                    param=(zone_code, zone_alias, parent_code, title, order))

    def _remove_zone(self, zone_code):
        sql = "DELETE FROM ucloud_agent.zone WHERE zone_code = %s"
        self.do_sql(sql=sql, param=zone_code)
